<template>
  <div class="json-editor">
    <textarea v-model="jsonInput" placeholder="请输入 JSON 内容..." />
    <div>
      <el-select v-model="useFn" placeholder="Select" size="large" style="width: 240px">
        <el-option v-for="item in config" :key="item.name" :label="item.label" :value="item" />
      </el-select>
      <button class="format-button" @click="formatJson">转换</button>
    </div>
    <div v-if="error" class="error-message">{{ error }}</div>
    <div>
      <button class="copy-button" @click="handlerCopy">copy</button>
      <pre v-if="result" v-html="result" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { copy } from "@/utils/copy";
import { ref } from "vue";
import { config } from "./config";
import { ConfigType } from "./type";

const jsonInput = ref("");
const result = ref("");
const error = ref("");
const useFn = ref<ConfigType>(config[0]);
const formatJson = async () => {
  if (!jsonInput.value) {
    error.value = "请输入 JSON 内容";
    return;
  }
  if (jsonInput.value.startsWith("'") && jsonInput.value.endsWith("'")) {
    jsonInput.value = jsonInput.value.slice(1, -1);
  }
  if (!useFn.value) {
    error.value = "请选择转换方式";
    return;
  }
  try {
    result.value = await useFn.value.fn(jsonInput.value);
    error.value = "";
  } catch (e) {
    console.error(e);
    error.value = "无效的 JSON 格式";
    result.value = jsonInput.value;
  }
};
const handlerCopy = async () => {
  await copy(result.value);
};
</script>

<style scoped>
.json-editor {
  width: 100%;
  height: 100%;
  padding: 20px;
  background-color: #2d2d44;
  border-radius: 8px;
}

textarea {
  width: 100%;
  height: 200px;
  padding: 10px;
  font-family: monospace;
  font-size: 14px;
  background-color: transparent;
  color: #ffffff;
  border: 1px solid #444;
  border-radius: 4px;
  resize: none;
}

.format-button {
  margin-top: 10px;
  margin-left: 20px;
  padding: 10px 20px;
  background-color: #42b983;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.format-button:hover {
  background-color: #3aa876;
}

pre {
  margin-top: 10px;
  padding: 10px;
  background-color: #1e1e2f;
  border-radius: 4px;
  color: #ffffff;
  white-space: pre-wrap;
  position: relative;
  overflow-y: scroll;
  height: 400px;
}

.error-message {
  margin-top: 10px;
  color: #ff4d4f;
}
.copy-button {
  width: 50px;
  text-align: center;
  border-radius: 4px;
  background-color: gray;
  color: white;
  height: 25px;
  position: absolute;
  z-index: 1000;
  right: 20px;
  cursor: pointer;
}
.copy-button:hover {
  background-color: #444;
}
</style>
